package com.cong.taoyao.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Tag(name = "文件上传")
@RestController
@RequestMapping
@Slf4j
public class FileUploadController {

    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 获取项目根目录下的templates目录
            String uploadDir = "src/main/resources/templates/";

            // 创建临时目录
            Path tempDir = Files.createTempDirectory("");

            // 将上传的ZIP文件保存到临时目录
            Path tempFile = tempDir.resolve(Objects.requireNonNull(file.getOriginalFilename()));
            Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

            // 解压ZIP文件到templates目录
            unzip(tempFile.toString(), uploadDir);

            // 删除临时文件
            Files.deleteIfExists(tempFile);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return "ok";
    }

    private void unzip(String zipFilePath, String destDir) throws IOException {
        try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(Path.of(zipFilePath)))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    Path entryPath = Path.of(destDir, entry.getName());
                    Files.createDirectories(entryPath.getParent());
                    Files.copy(zipInputStream, entryPath, StandardCopyOption.REPLACE_EXISTING);
                }
                zipInputStream.closeEntry();
            }
        }
    }
}
